//
//  SeriesViewController.m
//  CheXunWang
//
//  Created by zhu lin on 12/14/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "SeriesViewController.h"
#import "HttpServices.h"
#import "StorageService.h"
#import "HomeViewController.h"
#import "CheXunWangAppDelegate.h"
#import "SeriesInfoCell.h"
#import "CustomBarButtonItem.h"
#import <QuartzCore/QuartzCore.h>
#import "ModelListViewController.h"

/*
 {
 "english":"audi-q5",
 -"seriesId":2102,
 -"guidePrice":"37.98-56.77万元",
 -"imagePath":"http://photo.chexun.com/images/auto/2011-11/aodi/aodiq5/20tsidgx/12090/20111130153345771458490.jpg",
 "brandId":2,
 "companyId":81,
 "importType":"1",
 "recommendSort":"5",
 -"features":"奥迪最便宜的SUV，但是没和途观拉开档次，价格不占优势",
 "brandName":"奥迪",
 -"companyName":"一汽奥迪",
 -"guidePriceFor4S":"37.98-56.77万元",
 -"seriesName":"奥迪Q5"}
 */

#define kDefaultSectionNum		1
#define kDefaultCellNum			1
#define kCustomSectionHeight	20.0
#define kCustomCellHeight		100.0
#define kCustomBlankCellHeight	367.0

#define kSectionKey			@"companyName"
#define kImageKey			@"imagePath"
#define kSeriesNameKey		@"seriesName"
#define kPriceKey			@"guidePrice"

@interface SeriesViewController()
@property (nonatomic, retain) ASIHTTPRequest *serieslistRequest;
@property (nonatomic, retain) NSMutableDictionary *imageDownloadsInProgress;

- (void) showHomeView:(id)sender;
- (UIImage *)loadImageOfIndexPath:(NSIndexPath *)indexPath;
- (void)loadImagesForOnscreenRows;
@end


@implementation SeriesViewController
@synthesize hud, groupedSeriesArray;
@synthesize scopeValue;
@synthesize backType;
@synthesize serieslistRequest;
@synthesize imageDownloadsInProgress;

- (ATMHud *)hud
{
	if (hud == nil) {
		hud = [[ATMHud alloc] init];
		[self.view addSubview:hud.view];
	}
	return hud;
}

#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.hidesBackButton = YES;
	switch (self.backType) {
		case ZLBackButtonTypeHome:
		{
			UIButton *homeButton = [UIButton buttonWithType:UIButtonTypeCustom];
			homeButton.frame = CGRectMake(0.0f, 8.0f, 87.0f, 27.0f);
			[homeButton addTarget:self action:@selector(showHomeView:) forControlEvents:UIControlEventTouchUpInside];
			[homeButton setImage:[UIImage imageNamed:@"ios_common_titlebar_logo.png"] forState:UIControlStateNormal];
			self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:homeButton];
		}
			break;
		case ZLBackButtonTypeBrand:
		{
			CustomBarButtonItem *backButton = [[CustomBarButtonItem alloc] initWithTitle:@"品 牌" style:LeftBarButtonItemBackStyle target:self action:@selector(popViewController:)];
			self.navigationItem.leftBarButtonItem = backButton;
			[backButton release];
		}
			break;
		case ZLBackButtonTypeScope:
		{
			CustomBarButtonItem *backButton = [[CustomBarButtonItem alloc] initWithTitle:@"价格筛选" style:LeftBarButtonItemBackStyle target:self action:@selector(popViewController:)];
			self.navigationItem.leftBarButtonItem = backButton;
			[backButton release];
		}
			break;
		default:
			break;
	}
	
	self.tableView.tableFooterView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 0)] autorelease];
	
	self.groupedSeriesArray = [NSMutableArray array];
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
}

- (void)viewWillAppear:(BOOL)animated
{
	
}

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	int count = [self.groupedSeriesArray count];
	
    if (count == 0) {
		return kDefaultSectionNum;
	}
	
	return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([self.groupedSeriesArray count] == 0) {
		return kDefaultCellNum;
	}
	
    NSArray *subArray = [self.groupedSeriesArray objectAtIndex:section];
	if (subArray && [subArray count] > 0) {
		return [subArray count];
	}
	
	return kDefaultCellNum;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([self.groupedSeriesArray count] == 0) {
		return kCustomBlankCellHeight;
	}
	
	return kCustomCellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	if ([self.groupedSeriesArray count] == 0) {
		return nil;
	}
	
	UIView *customSectionView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, kCustomSectionHeight)];
	UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ios_common_list_title_bg.png"]];
	backImageView.frame = CGRectMake(0.0, 0.0, 320.0, kCustomSectionHeight);
	[customSectionView addSubview:backImageView];
	[backImageView release];
	UILabel *companyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 300.0f, kCustomSectionHeight)];
	companyLabel.backgroundColor = [UIColor clearColor];
	companyLabel.textColor = [UIColor colorWithRed: 0.2 green: 0.2 blue: 0.2 alpha: 1.0];
	companyLabel.font = [UIFont systemFontOfSize:12.0f];
	companyLabel.text = (NSString *)[[[self.groupedSeriesArray objectAtIndex:section] objectAtIndex:0] valueForKey:kSectionKey];
	[customSectionView addSubview:companyLabel];
	[companyLabel release];
	return customSectionView;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *blankCellIdentifier = @"blankCell";
	static NSString *seriesCellIdentifier = @"seriesCell";
    
	if ([self.groupedSeriesArray count] == 0) {
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:blankCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
										   reuseIdentifier:blankCellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		return cell;
	}
	
    SeriesInfoCell *cell = (SeriesInfoCell *)[tableView dequeueReusableCellWithIdentifier:seriesCellIdentifier];
    if (cell == nil)
	{
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SeriesInfoCell" owner:self options:nil];
		for(id oneNib in nib)
			if([oneNib isKindOfClass:[SeriesInfoCell class]])
				cell = (SeriesInfoCell *)oneNib;
		
		// set
		[cell.seriesImageView.layer setCornerRadius:15.0f];
		
		UIImage *backImage = [UIImage imageNamed:@"ios_common_list_item_normal.png"];
		UIImageView *backImageView = [[UIImageView alloc] initWithImage:[backImage stretchableImageWithLeftCapWidth:5.0 topCapHeight:10.0]];
		[cell setBackgroundView:backImageView];
		[backImageView release];
		
		UIImage *selectedBackImage = [UIImage imageNamed:@"ios_common_list_item_pressed.png"];
		UIImageView *selectedBackImageView = [[UIImageView alloc] initWithImage:[selectedBackImage stretchableImageWithLeftCapWidth:5.0 topCapHeight:10.0]];
		[cell setSelectedBackgroundView:selectedBackImageView];
		[selectedBackImageView release];
	}
    
    // Configure the cell...
	NSDictionary *dic = (NSDictionary *)[[self.groupedSeriesArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	cell.seriesNameLabel.text = (NSString *)[dic objectForKey:kSeriesNameKey];
	cell.seriesPriceLabel.text = (NSString *)[dic objectForKey:kPriceKey];
	cell.seriesImageView.image = [self loadImageOfIndexPath:indexPath];
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.groupedSeriesArray count] == 0) {
		return;
	}
	
	NSDictionary *dic = (NSDictionary *)[[self.groupedSeriesArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	
    ModelListViewController *seriesVC = [[ModelListViewController alloc] initWithNibName:@"ModelListViewController" bundle:nil];
	seriesVC.title = (NSString *)[dic objectForKey:kSeriesNameKey];
	seriesVC.seriesInfoDic = dic;
	seriesVC.scopeValue = self.scopeValue;
	
	//
	[self.navigationController pushViewController:seriesVC animated:YES];
	[seriesVC release];
	
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark image download methods
- (UIImage *)loadImageOfIndexPath:(NSIndexPath *)indexPath
{
	NSDictionary *dic = (NSDictionary *)[[self.groupedSeriesArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	NSString *imageURL = (NSString *)[dic valueForKey:kImageKey];
	NSString *imageName = (NSString *)[[imageURL componentsSeparatedByString:@"/"] lastObject];
	NSString *imagePath = [StorageService getPathByStorageType:ZLStorageTypeSeriesImage withFileName:imageName];
	
	if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
		return [UIImage imageWithContentsOfFile:imagePath];
	} else {
		ASIHTTPRequest *request = [self.imageDownloadsInProgress objectForKey:indexPath];
		if (request == nil && self.tableView.dragging == NO && self.tableView.decelerating == NO) {
			request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageURL]];
			[request setDelegate:self];
			[request setDownloadDestinationPath:imagePath];
			[request startAsynchronous];
			[self.imageDownloadsInProgress setObject:request forKey:indexPath];
		}
	}
	
	return [UIImage imageNamed:@"ios_common_list_item_avatar.png"];
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
	if ([self.groupedSeriesArray count] > 0)
	{
		NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
		for (NSIndexPath *indexPath in visiblePaths)
		{
			[self loadImageOfIndexPath:indexPath];
		}
	}
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}

- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate 
{
	if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

#pragma mark -
#pragma mark Memory management
- (void)viewDidDisappear:(BOOL)animated
{
	for(ASIHTTPRequest *request in [self.imageDownloadsInProgress allValues])
	{
		if (request != nil) {
			[request clearDelegatesAndCancel];
		}
	}
	[self.serieslistRequest clearDelegatesAndCancel];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
	for(ASIHTTPRequest *request in self.imageDownloadsInProgress)
	{
		if (request != nil) {
			[request clearDelegatesAndCancel];
		}
	}
	[self.serieslistRequest clearDelegatesAndCancel];
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
	self.hud = nil;
	self.groupedSeriesArray = nil;
	
	self.serieslistRequest = nil;
	self.imageDownloadsInProgress = nil;
}


- (void)dealloc {
	[serieslistRequest release];
	[imageDownloadsInProgress release];
	[groupedSeriesArray release];
	[hud release];
    [super dealloc];
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {
		NSData *responseData = [request responseData];
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		
		NSArray *ungroupedArray = (NSArray *)[result JSONValue];
		if (!ungroupedArray || [ungroupedArray count] == 0) {
			self.groupedSeriesArray = [NSMutableArray array];
		} else {
			self.groupedSeriesArray = [HttpServices groupArray:ungroupedArray byKey:kSectionKey];
		}
		
		[self.hud hide];
		[self.tableView reloadData];
	} else {
		// loadimage request
		NSIndexPath *indexPath = [imageRequestArray objectAtIndex:0];
		SeriesInfoCell *cell = (SeriesInfoCell *)[self.tableView cellForRowAtIndexPath:indexPath];;
		cell.seriesImageView.image = [self loadImageOfIndexPath:indexPath];
		[self.imageDownloadsInProgress removeObjectForKey:indexPath];
	}	
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {
		[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
		[self.hud setCaption:@"访问出错！"];
		[self.hud setImage:[UIImage imageNamed:@"11-x"]];
		[self.hud setActivity:NO];
		[self.hud update];
		[self.hud hideAfter:1.0f];
	} else {
		// stop loadimage
		NSIndexPath *indexPath = [imageRequestArray objectAtIndex:0];
		[self.imageDownloadsInProgress removeObjectForKey:indexPath];
	}
}

#pragma mark -
#pragma mark actions
- (void) getSeriesBySeriesName:(NSString *)seriesName
{
	// 查询车系
	self.serieslistRequest = [HttpServices getSeriesInfoByBrandID:nil 
							   companyID:nil 
								seriesID:nil
							  seriesName:seriesName 
							  priceScope:nil
								delegate:self];
	// show hud
	
	[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
	[self.hud setCaption:@"正在载入"];
	[self.hud setActivity:YES];
	[self.hud show];
}

- (void) getSeriesByBrandId:(NSString *)brandId
{
	self.serieslistRequest = [HttpServices getSeriesInfoByBrandID:brandId 
							   companyID:nil 
								seriesID:nil
							  seriesName:nil 
							  priceScope:nil
								delegate:self];
	// show hud
	
	[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
	[self.hud setCaption:@"正在载入"];
	[self.hud setActivity:YES];
	[self.hud show];
}

- (void) getSeriesByScope:(NSString*)scope
{
	self.serieslistRequest = [HttpServices getSeriesInfoByBrandID:nil 
														companyID:nil 
														 seriesID:nil
													   seriesName:nil 
													   priceScope:scope
														 delegate:self];
	// show hud
	
	[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
	[self.hud setCaption:@"正在载入"];
	[self.hud setActivity:YES];
	[self.hud show];
}

- (void)popViewController:(id)sender
{	
	[self.navigationController popViewControllerAnimated:YES];
}

- (void) showHomeView:(id)sender
{
	if (![NSThread isMainThread]) {
		[self performSelectorOnMainThread:@selector(backToHome:) withObject:nil waitUntilDone:NO];
		return;
	}
	
	HomeViewController *homeVC = [HomeViewController sharedViewController];
	[self.navigationController presentModalViewController:homeVC animated:YES];
	//UINavigationController *nav = [[CheXunWangAppDelegate shareAppDelegate].tabbarController.viewControllers objectAtIndex:0];
	//[nav popToRootViewControllerAnimated:NO];
	
	
	//[[[CheXunWangAppDelegate shareAppDelegate].tabbarController.viewControllers objectAtIndex:0] presentModalViewController:[HomeViewController sharedViewController] animated:NO];
}
@end

